package com.amsp.oa.oademo.service.impl;

import com.amsp.oa.oademo.entity.EnvironmentApply;
import com.amsp.oa.oademo.mapper.EnvironmentApplyMapper;
import com.amsp.oa.oademo.service.EnvironmentApplyService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.Random;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.ArrayList;

@Service
public class EnvironmentApplyServiceImpl extends ServiceImpl<EnvironmentApplyMapper, EnvironmentApply> implements EnvironmentApplyService {

    @Override
    public IPage<EnvironmentApply> getApplyList(Page<EnvironmentApply> page, String keyword, String type, String status) {
        LambdaQueryWrapper<EnvironmentApply> wrapper = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(keyword)) {
            wrapper.like(EnvironmentApply::getApplyNo, keyword)
                  .or()
                  .like(EnvironmentApply::getApplicant, keyword)
                  .or()
                  .like(EnvironmentApply::getArea, keyword);
        }
        
        if (StringUtils.hasText(type)) {
            wrapper.eq(EnvironmentApply::getType, type);
        }
        
        if (StringUtils.hasText(status)) {
            wrapper.eq(EnvironmentApply::getStatus, status);
        }
        
        wrapper.orderByDesc(EnvironmentApply::getCreateTime);
        
        return this.page(page, wrapper);
    }

    @Override
    public EnvironmentApply submitApply(EnvironmentApply apply) {
        try {
            // 1. 生成申请编号
            String applyNo = generateApplyNo(apply.getType());
            apply.setApplyNo(applyNo);
            
            // 2. 设置初始状态
            apply.setStatus("pending");
            
            // 3. 设置时间
            Date now = new Date();
            apply.setCreateTime(now);
            apply.setUpdateTime(now);
            
            // 4. 数据验证
            validateApply(apply);
            
            // 5. 保存数据
            this.save(apply);
            
            return apply;
        } catch (Exception e) {
            throw new RuntimeException("提交申请失败：" + e.getMessage());
        }
    }

    @Override
    public EnvironmentApply updateApply(EnvironmentApply apply) {
        apply.setUpdateTime(new Date());
        this.updateById(apply);
        return apply;
    }

    @Override
    public void deleteApply(Long id) {
        this.removeById(id);
    }

    @Override
    public EnvironmentApply getApplyByNo(String applyNo) {
        LambdaQueryWrapper<EnvironmentApply> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EnvironmentApply::getApplyNo, applyNo);
        return this.getOne(wrapper);
    }

    @Override
    public IPage<EnvironmentApply> getMyApplies(Page<EnvironmentApply> page, String applicant, String type) {
        LambdaQueryWrapper<EnvironmentApply> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EnvironmentApply::getApplicant, applicant);
        
        if (StringUtils.hasText(type)) {
            wrapper.eq(EnvironmentApply::getType, type);
        }
        
        wrapper.orderByDesc(EnvironmentApply::getCreateTime);
        return this.page(page, wrapper);
    }

    @Override
    public EnvironmentApply handleApply(Long id, String handler, String handleResult) {
        EnvironmentApply apply = this.getById(id);
        if (apply == null) {
            throw new IllegalArgumentException("申请不存在");
        }
        
        apply.setHandler(handler);
        apply.setHandleResult(handleResult);
        apply.setHandleTime(new Date());
        apply.setStatus("completed");
        apply.setUpdateTime(new Date());
        
        this.updateById(apply);
        return apply;
    }

    @Override
    public EnvironmentApply cancelApply(Long id) {
        EnvironmentApply apply = this.getById(id);
        if (apply == null) {
            throw new IllegalArgumentException("申请不存在");
        }
        
        if (!"pending".equals(apply.getStatus())) {
            throw new IllegalArgumentException("只能取消待处理的申请");
        }
        
        apply.setStatus("cancelled");
        apply.setUpdateTime(new Date());
        
        this.updateById(apply);
        return apply;
    }

    private String generateApplyNo(String type) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(new Date());
        String random = String.format("%03d", new Random().nextInt(1000));
        String prefix = "";
        switch (type) {
            case "clean":
                prefix = "QJ";
                break;
            case "disinfect":
                prefix = "XS";
                break;
            case "green":
                prefix = "LH";
                break;
            default:
                prefix = "HJ";
        }
        return prefix + dateStr + random;
    }

    private void validateApply(EnvironmentApply apply) {
        List<String> errors = new ArrayList<>();
        
        if (StringUtils.isEmpty(apply.getType())) {
            errors.add("申请类型不能为空");
        }
        if (StringUtils.isEmpty(apply.getApplicant())) {
            errors.add("申请人不能为空");
        }
        if (StringUtils.isEmpty(apply.getPhone())) {
            errors.add("联系电话不能为空");
        }
        if (StringUtils.isEmpty(apply.getArea())) {
            errors.add("区域不能为空");
        }
        if (StringUtils.isEmpty(apply.getSection())) {
            errors.add("区段/楼层不能为空");
        }
        if (StringUtils.isEmpty(apply.getSpot())) {
            errors.add("具体位置不能为空");
        }
        if (StringUtils.isEmpty(apply.getServiceType())) {
            errors.add("服务类型不能为空");
        }
        if (apply.getExpectedStartTime() == null) {
            errors.add("期望开始时间不能为空");
        }
        if (apply.getExpectedEndTime() == null) {
            errors.add("期望结束时间不能为空");
        }
        if (apply.getExpectedStartTime() != null && apply.getExpectedEndTime() != null 
            && apply.getExpectedEndTime().before(apply.getExpectedStartTime())) {
            errors.add("结束时间不能早于开始时间");
        }
        if (StringUtils.isEmpty(apply.getRequirements())) {
            errors.add("具体要求不能为空");
        }

        if (!errors.isEmpty()) {
            throw new IllegalArgumentException(String.join("\n", errors));
        }
    }
} 